//
//  MYRefreshControl.swift
//  NewMicroblog
//
//  Created by apple on 2016/10/30.
//  Copyright © 2016年 apple. All rights reserved.
//

import UIKit

private enum MYRefreshType:Int{
    case normal = 0
    case pulling = 1
    case refreshing = 2
}

private let controlHeight: CGFloat = 50

class MYRefreshControl: UIControl {
    
    /// 保存当前的ScrollView
    fileprivate var currentScroll: UIScrollView?
    
    /// 记录当前的刷新状态
    fileprivate var myRefreshType: MYRefreshType = .normal{
        didSet{
            switch myRefreshType {
            case .normal:
                freshView.isHidden = false
                UIView.animate(withDuration: 0.25, animations: { 
                    self.freshView.transform = CGAffineTransform.identity
                })
                indicatorView.stopAnimating()
                messageLabel.text = "下拉刷新"
                if oldValue == .refreshing {
                    UIView.animate(withDuration: 0.25, animations: { 
                        self.currentScroll?.contentInset.top -= controlHeight
                    })
                }
                
           case .pulling:
              UIView.animate(withDuration: 0.25, animations: { 
                self.freshView.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI))
              })
                messageLabel.text = "松手就刷新"
             //正在刷新
            case .refreshing:
                freshView.isHidden = true
                indicatorView.startAnimating()
                messageLabel.text = "正在刷新"
                UIView.animate(withDuration: 0.25, animations: { 
                    self.currentScroll?.contentInset.top += controlHeight
                })
                sendActions(for: .valueChanged)
            }
            
            
        }
        
    }
    
   override init(frame: CGRect) {
        super.init(frame: CGRect(x: 0, y: -controlHeight, width: UIScreen.main.bounds.width, height: controlHeight))
            setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func willMove(toSuperview newSuperview: UIView?) {
        if let scrollView = newSuperview as? UIScrollView{
            
           scrollView.addObserver(self, forKeyPath: "contentOffset", options: .new, context: nil)
            currentScroll = scrollView;
        }
        
    }
   
    /// 设置刷新视图
    private func setupUI(){
        
      backgroundColor = UIColor.red
      addSubview(freshView)
      addSubview(messageLabel)
        addSubview(indicatorView)
        freshView.translatesAutoresizingMaskIntoConstraints = false
        messageLabel.translatesAutoresizingMaskIntoConstraints = false
        indicatorView.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: freshView, attribute: .centerX, relatedBy:.equal, toItem: self, attribute: .centerX, multiplier: 1, constant: -35))
        addConstraint(NSLayoutConstraint(item: freshView, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: .leading, relatedBy: .equal, toItem: freshView, attribute: .trailing, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: .centerY, relatedBy: .equal, toItem: freshView, attribute: .centerY, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: indicatorView, attribute: .centerX, relatedBy: .equal, toItem: freshView, attribute: .centerX, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: indicatorView, attribute:.centerY , relatedBy: .equal, toItem: freshView, attribute: .centerY, multiplier: 1, constant: 0))
    }
    
    private lazy var freshView: UIImageView = UIImageView(image:UIImage(named: "tableview_pull_refresh"))
    private lazy var messageLabel: UILabel = {
        let lab = UILabel()
        lab.text = "下拉刷新"
        lab.textAlignment = .center
        return lab
    }()
    private lazy var indicatorView: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .gray)
    
    
    deinit {
        removeObserver(self, forKeyPath: "contentOffset")
    }
}
extension MYRefreshControl{
  ///kVO监听方法
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        
        /// 判断当前的currentScroll是否为空
        guard let scrollV = currentScroll  else {
            return
        }
        /// 设置临界点
        let maxY = scrollV.contentInset.top + controlHeight
        let contentOffsetY = scrollV.contentOffset.y
        
        if scrollV.isDragging {
            if contentOffsetY < maxY && myRefreshType == .normal{
               myRefreshType = .pulling
//                print("pulling")
            }else if contentOffsetY >= maxY && myRefreshType == .pulling{
                myRefreshType = .normal
//                print("normal")
            }
        }else{
            if myRefreshType == .pulling {
                myRefreshType = .refreshing
//                print("正在刷新")
            }
        }
        
    }
    //结束刷新
    func endRefreshing(){
        myRefreshType = .normal
    }
    
}
